package evi.com.evi.pager;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.classic.ClassicRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import evi.com.evi.R;
import evi.com.evi.adapter.PendingOrderAdapter;
import evi.com.evi.application.MyApplication;
import evi.com.evi.bean.DisposeOrderBean;
import evi.com.evi.fragment.DisposeFalseFragment;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.SPUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 待确认
 * Created by sunyu on 2017/3/11.
 */

public class PendingOrderPager extends BasePager implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    private View view;
    private RecyclerView can_content_view;
    private List<DisposeOrderBean> list;
    private PendingOrderAdapter adapter;
    private CanRefreshLayout refresh;
    private ClassicRefreshView can_refresh_header;
    private ClassicRefreshView can_refresh_footer;
    private OkHttpClient client;
    private JSONUtils jsonUtil;

    public DisposeFalseFragment disposeFalseFragment;

//    private Dialog dialog;

    @Override
    public void flushFilter(String text){
        adapter.getFilter().filter(text);
    }

    public PendingOrderPager(Activity activity, Fragment fragment) {
        super(activity);
        this.disposeFalseFragment = (DisposeFalseFragment) fragment;
    }

    @Override
    public void initData() {
        super.initData();

        if (client == null) {
            client = new OkHttpClient();
        }
        if (jsonUtil == null) {
            jsonUtil = new JSONUtils();
        }

        if (view == null) {
            view = View.inflate(activity, R.layout.confirmed_pager, null);
            can_content_view = (RecyclerView) view.findViewById(R.id.can_content_view);
            LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
            can_content_view.setLayoutManager(layoutManager);

            can_refresh_header = (ClassicRefreshView) view.findViewById(R.id.can_refresh_header);
            can_refresh_footer = (ClassicRefreshView) view.findViewById(R.id.can_refresh_footer);

            can_refresh_header.setRefreshingStr("正在刷新");
            can_refresh_header.setPullStr("下拉刷新");
            can_refresh_header.setReleaseStr("松手刷新");
            can_refresh_header.setCompleteStr("刷新完成");

            can_refresh_footer.setRefreshingStr("正在加载");
            can_refresh_footer.setPullStr("上拉加载");
            can_refresh_footer.setReleaseStr("松手加载更多");
            can_refresh_footer.setCompleteStr("加载完成");

            refresh = (CanRefreshLayout) view.findViewById(R.id.refresh);
            //下拉刷新
            refresh.setOnRefreshListener(this);
            //上拉加载
            refresh.setOnLoadMoreListener(this);
            //刷新样式
            refresh.setStyle(0, 0);



            list = new ArrayList<>();


            adapter = new PendingOrderAdapter(activity, list, this);
            can_content_view.setAdapter(adapter);
            fl_basepager.addView(view);


        }
        onRefresh();

    }

    private void getOrderInfoFromServer() {
        String token = SPUtil.getString(MyApplication.getInstance().getApplicationContext(), "token");
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.queryWaitOrder_url)
                .build();

//        //测试专用，测试完后，需要注释，上面4行需要放开
//        Log.e("ee url==",ContentUtils.queryHisStatus=" );
//        Request request = new Request.Builder().addHeader("ttOrder_url+"?dateRangeType=2&orderoken", token)
//                .url(ContentUtils.queryHistOrder_url+"?dateRangeType=2&orderStatus=")
//                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("DisposeTrueFragment", "取订单信息失败");
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ConnectUtil.isConnect(activity)) {
                            Toast.makeText(activity, "网络信号不佳，加载失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(activity, "网络未联接，请检查", Toast.LENGTH_SHORT).show();
                        }
//                        Toast.makeText(activity, "网络信号不佳，加载失败", Toast.LENGTH_SHORT).show();

//                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                Log.e("待确认界面联网", "PendingOrderPager = " + jsonData);
                if (jsonUtil.validate(jsonData)) {
                    //,SerializerFeature.WriteNullStringAsEmpty
                    final JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
//                        list.clear();
                        adapter.clearResult();
                        JSONArray ary = jsonObject.getJSONArray("data");
                        if (ary != null) {
                            Log.e("DisposeTrueFragment", "取订单成功,count=" + ary.size());
                            for (int i = 0; i < ary.size(); i++) {
                                JSONObject obj = ary.getJSONObject(i);
//                                list.add(new DisposeOrderBean(obj));
                                adapter.addResult(new DisposeOrderBean(obj));
                            }
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                    adapter.notifyDataSetChanged();
                                    if( disposeFalseFragment.searchText == null || disposeFalseFragment.searchText.getText().length()==0 ){
                                        adapter.notifyDataSetChanged();
                                    }else{
                                        adapter.getFilter().filter(""+disposeFalseFragment.searchText.getText().toString());
                                    }
                                    disposeFalseFragment.getCount(PendingOrderPager.this, adapter.getResultSize() + "");
//                                    dialog.dismiss();
                                }
                            });
                        }

                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
//                                dialog.dismiss();
                            }
                        });
                    }
                }
            }
        });

    }

    public void sendDealOrderRequest(String orderId, Integer newStatus, String reason, final int position) {
        Log.e("EE", "orderId=" + orderId + ", status=" + newStatus + ", reason=" + reason);

        String token = SPUtil.getString(MyApplication.getInstance().getApplicationContext(), "token");
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.dealOrder_url + "?orderId=" + orderId + "&newStatus=" + newStatus + "&reason=" + reason)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ConnectUtil.isConnect(activity)) {
                            Toast.makeText(activity, "网络信号不佳，加载失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(activity, "网络未联接，请检查", Toast.LENGTH_SHORT).show();
                        }
//                        Toast.makeText(activity, "网络信号不佳，加载失败", Toast.LENGTH_SHORT).show();
//                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                Log.e("PendingOrderAdapter", jsonData);

                if (jsonUtil.validate(jsonData)) {
                    //,SerializerFeature.WriteNullStringAsEmpty
                    final JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {

                        list.remove(position);
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                disposeFalseFragment.getCount(PendingOrderPager.this, list.size() + "");
                                Toast.makeText(activity, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                                adapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                onRefresh();
                                Toast.makeText(activity, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        });
    }

    @Override
    public void onRefresh() {
//        dialog = AppUtils.getLoadingDialog(activity, "提示", "正在查询订单，请稍等");
//        dialog.show();
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages = 0;
                list.clear();
                adapter.notifyDataSetChanged();
                getOrderInfoFromServer();
                refresh.refreshComplete();
            }
        }, 1000);
    }

    private int pages;

    @Override
    public void onLoadMore() {
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages++;
                getOrderInfoFromServer();
                can_refresh_footer.setCompleteStr("");
                refresh.loadMoreComplete();
            }
        }, 1000);

    }
}